package com.java2nb.novel.pay.controller;

import com.alibaba.fastjson.JSON;
import com.java2nb.novel.pay.service.PayOrderService;
import com.java2nb.novel.pay.vo.PayOrderRequestVO;
import com.java2nb.novel.pay.vo.PayOrderResponseVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一支付下单控制器
 */
@RestController
@RequestMapping("/api/pay")
@Api(tags = "支付下单接口")
@Slf4j
public class PayOrderController {
    @Autowired
    private PayOrderService payOrderService;

    /**
     * 统一支付下单接口
     * @param request 下单请求（JSON格式）
     * @param httpServletRequest HTTP请求（用于获取客户端IP，可选）
     * @return 下单响应
     */
    @PostMapping("/unifiedOrder")
    @ApiOperation("统一支付下单")
    public PayOrderResponseVO unifiedOrder(
            @Validated @RequestBody PayOrderRequestVO request,
            HttpServletRequest httpServletRequest
    ) {
        // 补充客户端IP（如果请求中未传）
        if (request.getClientIp() == null || request.getClientIp().isEmpty()) {
            String clientIp = getClientIp(httpServletRequest);
            request.setClientIp(clientIp);
            log.info("自动填充客户端IP：{}", clientIp);
        }

        log.info("接收支付下单请求：{}", JSON.toJSONString(request));
        PayOrderResponseVO response = payOrderService.createOrder(request);
        log.info("支付下单响应：{}", JSON.toJSONString(response));
        return response;
    }

    /**
     * 获取客户端真实IP（处理代理场景）
     * @param request HTTP请求
     * @return 客户端IP
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 处理多IP场景（如X-Forwarded-For: 192.168.1.1, 10.0.0.1），取第一个非unknown的IP
        if (ip != null && ip.contains(",")) {
            String[] ips = ip.split(",");
            for (String tmpIp : ips) {
                if (!"unknown".equalsIgnoreCase(tmpIp.trim())) {
                    ip = tmpIp.trim();
                    break;
                }
            }
        }
        return ip;
    }
}